<?php
class Xend_Db_Model {
	protected $_dbTableName;
	protected $_dbTable;
	protected $_database;

	protected function __construct() {
		$config 					= new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
		$this->_database	= Zend_Db::factory($config->resources->db);
		$this->_database->setFetchMode(Zend_Db::FETCH_NUM);
	}

	public function setDbTable($dbTable) {
		if(is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if(!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid Table Data Gateway ' . (string) $dbTable);
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable() {
		if(null === $this->_dbTable) {
			$this->setDbTable($this->_dbTableName);
		}

		return $this->_dbTable;
	}

	/**
	 * entfernt Eintraege, die auf die Bedingung $where zutreffen, aus der Tabelle
	 * queue_resources
	 * @param array $where Bedingungen
	 * @param int Anzahl der betroffenen Datensaetze
	 */
	public function remove($where) {

		// es sollte mindestens eine Bedingung vorhanden sein, es soll ja nicht die Tabelle
		// geleert werden
		if(is_array($where) === false || empty($where) === true) {
			return 0;
		}

		// Query-Builder fuer Where-Aufbau verwenden
		$select = $this->_database->select();
		foreach($where as $k => $v) {
			$select->where($this->getDbTable()->getAdapter()->quoteInto($k, $v));
		}

		return $this->getDbTable()->delete($select->getPart(Zend_Db_Select::WHERE));
	}

	protected function fetchMeta($stmt) {
		$meta = array();

		for($i = 0; $n = $stmt->columnCount(), $n > $i; $i++) {
			$meta[$i] = $stmt->getColumnMeta($i);
		}

		return $meta;
	}

	protected function fetch($select) {
		$stmt = $this->_database->query($select);
		$meta = $this->fetchMeta($stmt);
		$data = array();

		while($row = $stmt->fetch()) {
			$arr = array();

			foreach($row as $j => $value) {
				if(!array_key_exists($meta[$j]['table'], $arr)) {
					$arr[$meta[$j]['table']] = array();
				}

				$arr[$meta[$j]['table']][$meta[$j]['name']] = $value;
			}

			$data[] = $arr;
		}

		return $data;
	}
}
?>